const fs = require("fs");
const path = require("path");
const glob = require("glob"); // 需要安装 glob: npm install glob

// 配置你的项目目录和别名
const PROJECT_ROOT = path.join(__dirname, "src");
const ALIAS_MAP = {
  "@": PROJECT_ROOT,
};

// 要检查的文件类型
const EXTENSIONS = [".vue", ".js", ".ts", ".jsx", ".tsx"];

// 查找所有引用路径
function findImportPaths(fileContent) {
  const importRegex = /(?:import|from|require\()\s*['"]([^'"]+)['"]/g;
  const paths = [];
  let match;
  while ((match = importRegex.exec(fileContent)) !== null) {
    paths.push(match[1]);
  }
  return paths;
}

// 检查路径是否存在且大小写匹配
function checkPathExists(importPath, filePath) {
  if (importPath.startsWith(".")) {
    const absPath = path.resolve(path.dirname(filePath), importPath);
    return fs.existsSync(absPath) && fs.realpathSync(absPath) === absPath;
  }

  // 处理别名路径
  for (const [alias, aliasPath] of Object.entries(ALIAS_MAP)) {
    if (importPath.startsWith(alias)) {
      const relPath = importPath.replace(alias, "");
      const absPath = path.resolve(aliasPath, `.${relPath}`);
      return fs.existsSync(absPath) && fs.realpathSync(absPath) === absPath;
    }
  }

  return true; // 忽略 node_modules 等外部引用
}

// 主检查函数
function checkAllFiles() {
  const files = glob.sync(`${PROJECT_ROOT}/**/*.{${EXTENSIONS.join(",")}}`);
  let hasError = false;

  files.forEach((file) => {
    const content = fs.readFileSync(file, "utf-8");
    const importPaths = findImportPaths(content);

    importPaths.forEach((importPath) => {
      if (!checkPathExists(importPath, file)) {
        console.error(`❌ 大小写不匹配: 在文件 ${file} 中引用 ${importPath}`);
        hasError = true;
      }
    });
  });

  if (!hasError) {
    console.log("✅ 所有路径引用的大小写检查通过");
  } else {
    process.exit(1); // 发现错误时退出码为1
  }
}

checkAllFiles();
